package utils

import (
	"context"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/clientcmd"
)

// ListCRDs 使用DynamicClient列出集群中的CRDs
func ListCRDs() error {
	// 加载kubeconfig配置
	kubeconfig := "/path/to/kubeconfig" // 替换为实际的kubeconfig路径
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		return fmt.Errorf("failed to load kubeconfig: %v", err)
	}

	// 创建DynamicClient
	dynamicClient, err := dynamic.NewForConfig(config)
	if err != nil {
		return fmt.Errorf("failed to create dynamic client: %v", err)
	}

	// 定义CRD的GroupVersionResource
	gvr := schema.GroupVersionResource{
		Group:    "apiextensions.k8s.io",
		Version:  "v1",
		Resource: "customresourcedefinitions",
	}

	// 获取CRD列表
	crdList, err := dynamicClient.Resource(gvr).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return fmt.Errorf("failed to list CRDs: %v", err)
	}

	// 打印结果
	for _, crd := range crdList.Items {
		fmt.Printf("CRD: %s\n", crd.GetName())
	}

	return nil
}
